package MONITORING::MW::TOMCAT::SESSIONS;

#################################################################
# $LastChangedDate: 2013-11-25 15:03:06 +0000 (Mon, 25 Nov 2013) $
# $LastChangedRevision: 22 $
# $LastChangedBy: aswod_83@gmx.net $
#################################################################
use strict;
use base qw(moniCA::HTTP::REQUEST);
use XML::Simple;
use Data::Dumper;

#-------------------------------------------------------------------------------
sub Run {

#-------------------------------------------------------------------------------
# Description:
# Input Parms:
# Output Parms:
#-------------------------------------------------------------------------------
    my $self      = shift;
    my $cnf       = $self->GetCNF();
    my $logger    = $self->GetLogger();
    my $statefile = $self->TmpDir() . '/' . $self->Plug() . '.xml';
    my $ref;
    my $oldstat;
    my %newstat;

    if ( -s $statefile ) {
        $oldstat = XMLin( $statefile, ForceArray => 1 );
    }

    $self->ConnectHTTP(@_);

    if ( $self->{HTTPRequest}->is_success ) {

        foreach my $line ( $self->{HTTPRequest}->content =~ m/^.*$/ogm ) {
            chomp $line;
            next unless $line =~ m/running|stopped/g;
            my (
                $context_name,     $context_status,
                $context_sessions, $context_path
            ) = split( /:/, $line );

            $self->{sessions}->{$context_name} = $context_sessions;

            if ( $cnf->{sessions}->{$context_name} ) {

                $self->Report($context_name)
                  if (
                    $cnf->{sessions}->{$context_name}->{'Report'} =~ /true/i );

                if ( $context_sessions >=
                    $cnf->{sessions}->{$context_name}->{failCount} )
                {
                    $newstat{sessions}{$context_name}{failCount} =
                      ( $oldstat->{sessions}->{$context_name}->{failCount} + 1 )
                      || 1;
                    $newstat{sessions}{$context_name}{warnCount} = 0;
                    if ( $newstat{sessions}{$context_name}{failCount} ==
                        $cnf->{maxCount} )
                    {
                        $logger->error( "[Webapp: "
                              . $context_name
                              . "] Sessions: "
                              . $context_sessions
                              . " ($newstat{sessions}{$context_name}{failCount})"
                        );
                    }
                    else {
                        $logger->warn( "[Webapp: "
                              . $context_name
                              . "] Sessions: "
                              . $context_sessions
                              . " ($newstat{sessions}{$context_name}{failCount})"
                        );
                    }
                }
                elsif ( $context_sessions >=
                    $cnf->{sessions}->{$context_name}->{warnCount} )
                {
                    $newstat{sessions}{$context_name}{warnCount} =
                      ( $oldstat->{sessions}->{$context_name}->{warnCount} + 1 )
                      || 1;
                    $newstat{sessions}{$context_name}{failCount} = 0;
                    if ( $newstat{sessions}{$context_name}{warnCount} ==
                        $cnf->{maxCount} )
                    {
                        $logger->warn( "[Webapp: "
                              . $context_name
                              . "] Sessions: "
                              . $context_sessions
                              . " ($newstat{sessions}{$context_name}{warnCount})"
                        );
                    }
                    else {
                        $logger->warn( "[Webapp: "
                              . $context_name
                              . "] Sessions: "
                              . $context_sessions
                              . " ($newstat{sessions}{$context_name}{warnCount})"
                        );
                    }
                }
                else {
                    $newstat{sessions}{$context_name}{failCount} = 0;
                    $newstat{sessions}{$context_name}{warnCount} = 0;
                    $logger->info( "[Webapp: "
                          . $context_name
                          . "] Sessions: "
                          . $context_sessions );
                }
            }
            else {
                $logger->debug( "missing config parameter [Instance: ][Webapp: "
                      . $context_name
                      . "]" );
                next;
            }
        }
        $newstat{connection} = 0;
    }
    else {
        $newstat{connection} = ( $oldstat->{connection} + 1 ) || 1;
        $newstat{sessions} = $oldstat->{sessions};
        if ( $newstat{connection} == $cnf->{maxCount} ) {
            $logger->error(
                "Request: " . $cnf->{'HTTPConnect'}->{'HTTP_URL'} . " (",
                $self->{HTTPRequest}->status_line, ")" );
        }
        else {
            $logger->warn(
                "Request: " . $cnf->{'HTTPConnect'}->{'HTTP_URL'} . " (",
                $self->{HTTPRequest}->status_line, ")" );
        }

    }
    XMLout( \%newstat, outputfile => $statefile, NoSort => 0 );

}

#-------------------------------------------------------------------------------
sub Report {

#-------------------------------------------------------------------------------
# Description:
# Input Parms:
# Output Parms:
#-------------------------------------------------------------------------------
    my $self         = shift;
    my $context_name = shift;
    my $logger       = $self->GetLogger();
    my $cnf          = $self->GetCNF();

    eval {
        require RRDs;

        if (  !-f $self->VarDir() . '/'
            . $self->Plug() . '_'
            . $cnf->{sessions}->{$context_name}->{'ReportID'}
            . '.rrd' )
        {
            RRDs::create(
                $self->VarDir() . '/'
                  . $self->Plug() . '_'
                  . $cnf->{sessions}->{$context_name}->{'ReportID'} . '.rrd',
                "--step=300",
                "DS:sessionactive:GAUGE:600:0:10000",
                "RRA:AVERAGE:0.5:1:800",
                "RRA:AVERAGE:0.5:6:800",
                "RRA:AVERAGE:0.5:24:800",
                "RRA:AVERAGE:0.5:288:800",
                "RRA:MAX:0.5:1:800",
                "RRA:MAX:0.5:6:800",
                "RRA:MAX:0.5:24:800",
                "RRA:MAX:0.5:288:800"
            );
            $logger->warn( "RRDs::create returns " . RRDs::error() )
              if ( RRDs::error() );
        }

        if (  -f $self->VarDir() . '/'
            . $self->Plug() . '_'
            . $cnf->{sessions}->{$context_name}->{'ReportID'}
            . '.rrd' )
        {
            RRDs::update(
                $self->VarDir() . '/'
                  . $self->Plug() . '_'
                  . $cnf->{sessions}->{$context_name}->{'ReportID'} . '.rrd',
                '--template=sessionactive',
                'N' . ':' . $self->{sessions}->{$context_name}
            );

            $logger->warn( "RRDs::update returns " . RRDs::error() )
              if ( RRDs::error() );
        }
        1;
    } or $logger->info( "Report incomplete: " . $@ );

}

1;

__END__
 
=pod
 
=head1 NAME
 
SESSION.pm - monitors service availability 
 
=head1 SYNOPSIS
 
=head1 DESCRIPTION
 
=head1 PREREQUISITES
 
The follwing CPAN modules needs to be installed:
 
C<Log::Log4perl>
C<XML::Simple>
C<IO::Socket::INET>
C<Time::HiRes>
=head1 CONFIGURATION FILE
 
  By default
 
=head2 EXAMPLES
 
=head3 example of configuation file
 
Modul 	    MONITORING::SYS::SOCKET_PORT
Logger		%LOGGER%
LogLevel	%PRIORITY%


<service %IDENTIFIER%>
						PeerAddr = %DESTINATION_IP%
 						PeerPort = %DESTINATION_PORT%
 						Proto = %PROTOCOL%
 						Timeout	= %TIMEOUT_SEC%
 						LocalAddr = %LOCAL_BIND_IP%
</service>

max_error_count =       3
 
=cut
